package com.dayaokeji.rhythmschoolstudent.client.home.meeting;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.data.bean.QueryConditionBean;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.SchoolApi;
import com.dayaokeji.server_api.domain.School;
import com.dayaokeji.server_api.domain.UserInfo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 选择参与人员
 */
public class ChooseParticipantsActivity extends BaseActivity {

    public static final String EXTRA_CHOOSER_PARTICIPANTS = "participants";

    private static final int FLAG_CHOOSE_TYPE_DEPARTMENT = 1;
    private static final int FLAG_CHOOSE_TYPE_PROFESSION = 2;
    private static final int FLAG_CHOOSE_TYPE_CLASS = 3;


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_choose_department)
    TextView tvChooseDepartment;
    @BindView(R.id.tv_choose_profession)
    TextView tvChooseProfession;
    @BindView(R.id.tv_choose_class)
    TextView tvChooseClass;
    @BindView(R.id.tv_query_tips)
    TextView tvQueryTips;

    private static final SchoolApi schoolApi = ApiUtils.getApi(SchoolApi.class);
    private Call<ServerResponse<List<School>>> departmentCall;
    private ParticipantsListFragment participantsListFragment;

    public static List<UserInfo> CHOOSER_USERS;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_participants);
        setSupportActionBar(toolbar);
        CHOOSER_USERS = ((List<UserInfo>) getIntent().getSerializableExtra(EXTRA_CHOOSER_PARTICIPANTS));
        if (CHOOSER_USERS == null) {
            CHOOSER_USERS = new ArrayList<>();
        }

        init();
    }

    private void init() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        participantsListFragment = ParticipantsListFragment.newInstance();
        fragmentTransaction.replace(R.id.content, participantsListFragment);
        fragmentTransaction.commit();

        tvQueryTips.setText(getString(R.string.fuzzy_query,(CHOOSER_USERS.size()-1)));
        setOnListener();
    }

    private void setOnListener() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        if (participantsListFragment != null) {
            participantsListFragment.setOnSelectListener(new ParticipantsListFragment.OnSelectListener() {
                @Override
                public void onSelect(UserInfo userInfo) {
                    if (CHOOSER_USERS.contains(userInfo)) {
                        CHOOSER_USERS.remove(userInfo);
                    }else{
                        CHOOSER_USERS.add(userInfo);
                    }
                    tvQueryTips.setText(getString(R.string.fuzzy_query,(CHOOSER_USERS.size()-1)));
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent = getIntent();
        intent.putExtra(EXTRA_CHOOSER_PARTICIPANTS, (Serializable) CHOOSER_USERS);
        setResult(RESULT_OK,intent);
        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.choose_participants, menu);

        SearchView searchView = (SearchView) menu.findItem(R.id.menu_search_member).getActionView();
        searchView.setIconified(false);
        searchView.setIconifiedByDefault(false);
        searchView.onActionViewExpanded();
        searchView.setMaxWidth(1000);
        searchView.setQueryHint(getString(R.string.search_member));
        searchView.setOnQueryTextListener(queryTextListener);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 搜索栏文字变化监听
     */
    private final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            if (participantsListFragment != null) {
                participantsListFragment.queryKeyword(query);
            }
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            if (participantsListFragment != null) {
                participantsListFragment.queryKeyword(newText);
            }
            return false;
        }
    };


    @OnClick({
            R.id.tv_choose_department,
            R.id.tv_choose_profession,
            R.id.tv_choose_class
    })
    public void onClick(View view) {
        AndroidUtils.hideSoftInput(getWindow());
        switch (view.getId()) {
            case R.id.tv_choose_department:
                getQueryConditionList(UserUtils.getUserInfo().getUniversityId(),"选择院系",FLAG_CHOOSE_TYPE_DEPARTMENT);
                break;
            case R.id.tv_choose_profession:
                if (tvChooseDepartment.getTag() != null) {
                    getQueryConditionList((Long) tvChooseDepartment.getTag(), "选择专业", FLAG_CHOOSE_TYPE_PROFESSION);
                }else {
                    ToastUtils.info("请先选择院系");
                }
                break;
            case R.id.tv_choose_class:
                if (tvChooseProfession.getTag() != null) {
                    getQueryConditionList((Long) tvChooseProfession.getTag(), "选择专业",FLAG_CHOOSE_TYPE_CLASS);
                }else {
                    ToastUtils.info("请先选择专业");
                }
                break;
        }
    }

    /**
     * 获取查询条件list
     */
    private void getQueryConditionList(long parentId, final String title, final int chooseType) {
        departmentCall = schoolApi.department(parentId);
        departmentCall.enqueue(new ServerCallback<List<School>>(this,"正在获取数据...") {
            @Override
            public void onResponse(boolean success, ServerResponse<List<School>> response) {
                if (success) {
                    List<School> schoolList = response.getBody();
                    List<QueryConditionBean> queryConditionBeanList = new ArrayList<>();
                    for (School school : schoolList) {
                        QueryConditionBean queryConditionBean = new QueryConditionBean();
                        queryConditionBean.setName(school.getName());
                        queryConditionBean.setCode(school.getCode());
                        queryConditionBean.setId(school.getId());
                        queryConditionBean.setLevel(school.getLevel());
                        queryConditionBean.setParentCode(school.getParentCode());
                        queryConditionBeanList.add(queryConditionBean);
                    }

                    if (!isFinishing()) {
                        if (queryConditionBeanList.size() != 0) {
                            showChooseDepartmentDialog(queryConditionBeanList,title,chooseType);
                        }else{
                            ToastUtils.info("暂无数据");
                        }
                    }
                }
            }
        });
    }

    /**
     * 显示选择条件dialog
     * @param queryConditionBeanList
     * @param title
     * @param chooseType
     */
    private void showChooseDepartmentDialog(final List<QueryConditionBean> queryConditionBeanList, String title, final int chooseType) {
       final OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int i, int i1, int i2, View view) {
                QueryConditionBean queryConditionBean = queryConditionBeanList.get(i);
                if (queryConditionBean != null) {
                    switch (chooseType){
                        case FLAG_CHOOSE_TYPE_DEPARTMENT:
                            if (tvChooseDepartment != null) {
                                tvChooseDepartment.setText(queryConditionBean.getName());
                                tvChooseDepartment.setTag(queryConditionBean.getId());
                                if (participantsListFragment != null) {
                                    participantsListFragment.queryDepartment(queryConditionBean.getId());
                                }
                                if (tvChooseProfession != null && tvChooseClass != null) {
                                    tvChooseProfession.setText("选择专业");
                                    tvChooseProfession.setTag(null);
                                    tvChooseClass.setText("选择班级");
                                    tvChooseClass.setTag(null);
                                }
                            }
                            break;
                        case FLAG_CHOOSE_TYPE_PROFESSION:
                            if (tvChooseProfession != null) {
                                tvChooseProfession.setText(queryConditionBean.getName());
                                tvChooseProfession.setTag(queryConditionBean.getId());
                                if (participantsListFragment != null && tvChooseDepartment != null) {
                                    long departmentId = tvChooseDepartment.getTag() == null?0:(Long) tvChooseDepartment.getTag();
                                    participantsListFragment.queryPersonal(departmentId,queryConditionBean.getId());
                                }
                                if (tvChooseClass != null) {
                                    tvChooseClass.setText("选择班级");
                                    tvChooseClass.setTag(null);
                                }
                            }
                            break;
                        case FLAG_CHOOSE_TYPE_CLASS:
                            if (tvChooseClass != null) {
                                tvChooseClass.setText(queryConditionBean.getName());
                                tvChooseClass.setTag(queryConditionBean.getId());
                                if (participantsListFragment != null && tvChooseDepartment != null && tvChooseProfession != null) {
                                    long departmentId = tvChooseDepartment.getTag() == null ? 0 : (long) tvChooseDepartment.getTag();
                                    long personalId = tvChooseProfession.getTag() == null ? 0 : (long) tvChooseProfession.getTag();
                                    participantsListFragment.queryClass(departmentId,personalId,queryConditionBean.getId());
                                }
                            }
                            break;
                    }

                }
            }
        })
               .setTitleText(title)
               .build();
       optionsPickerView.setPicker(queryConditionBeanList);
       optionsPickerView.show();
    }

    @Override
    protected void onDestroy() {
        if (departmentCall != null) {
            departmentCall.cancel();
        }
        super.onDestroy();
    }
}
